package com.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDto;
import com.wanxi.model.UserModel;
import com.wanxi.service.Impl.UserServiceImpl;
import com.wanxi.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Li
 * @Date 2023/5/6 15:13
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//    乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //接收前端传过来的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String vCode = (String) req.getSession().getAttribute("vCode");
        //封装model
        UserModel userModel = UserModel.builder()
                .username(username)
                .password(password)
                .code(code)
                .vCode(vCode)
                .build();
        //调用service层
        UserService userService = new UserServiceImpl();
        ResultDto resultDto = userService.login(userModel);
        if ("success".equals(resultDto.getMsg())){
            req.getSession().setAttribute("username",username);
        }
        //返回数据
        resp.getWriter().println(JSONObject.toJSONString(resultDto));
    }
}
